package com.misc.pebblewatch;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * source http://stackoverflow.com/questions/4447477/android-how-to-copy-files-from-assets-folder-to-sdcard
 * License: code sample / public domain
 */
public class CopyAssets {

    public String lastDestinationFilename = null;

    public void copyAssets(Context inContext, String filePattern) {
        AssetManager assetManager = inContext.getAssets();
        String[] files = null;
        try {
            files = assetManager.list("");
        } catch (IOException e) {
            Log.e("CopyAssets", "Failed to get asset file list.", e);
        }
        for(String filename : files) {
            if (filename.contains(filePattern)) {
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = assetManager.open(filename);
                    File outFile = new File(inContext.getExternalFilesDir(null), filename);
                    out = new FileOutputStream(outFile);
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                    lastDestinationFilename = outFile.toString();
                } catch (IOException e) {
                    Log.e("CopyAssets", "Failed to copy asset file: " + filename, e);
                }
            }
        }
    }

    public void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }
}
